---
--类名: CaptainMessageView.lua
--创建日期: 2018-9-22
--创建人: 宋建邦
--功能描述: 留言板view
--修改内容:
local AvatarFactotry = require("app.public.avatar.AvatarFactory")

local Res = {
    CaptainMessageView = "ui2/room/Scene_social.csb",
    MessageNode = "ui2/room/Node_list.csb",
}

local CaptainMessageView = class("CaptainMessageView", app.mvc.ViewBase)
CaptainMessageView.VIEW_ROOT_RES = Res.CaptainMessageView

function CaptainMessageView:init()
    self:setBackGroundColorType(0)
    self:setNodeEventEnabled(true)

    local l = ccui.Layout:create()
    l:setContentSize(cc.size(display.width, display.height))
    l:setBackGroundColor(display.COLOR_BLACK)
    l:setBackGroundColorType(1)
    l:setTouchEnabled(false)
    l:setLocalZOrder(-1)
    l:setOpacity(255*0.8)
    self:addChild(l)
    self._root:findChild("Panel/Button_close"):addClickEventListener(function(sender)
        app:sendMsg("CaptainController", "closeMessageView")
    end)

    self.listNode = cc.CSLoader:createNode(Res.MessageNode)
    self.listNode:retain()
    self.currentTab = 1

    self:initMessageList()
    self:initVisitorList()
    self:initInputPanel()
    self:initEmptyTips()
    self:initSetingPanel()

    self:initTabs()

    self:hideAllPanel()
    self:showMessagePanel()

    self:initEvents()

    self:refreshRedPoint()
    -- app:sendMsg("CaptainController", "reqRoomData", UD.uid)
end

function CaptainMessageView:onExit()
    if self.currentTab == 3 then
        self:checkAndSendSetting()
    end

    self.listNode:release()
    EM:remove(self.msglistHandler)
    EM:remove(self.roomdataHandler)
    EM:remove(self.redpointHandler)
    
    if self:isSelf() then
        app:sendMsg("CaptainModelRedPoint", "reqClearMessageRedPoint")
    end
end

function CaptainMessageView:initEvents()
    local function onChangeEvent()
        local curModel = app:sendMsg("CaptainController", "getRoomData")
        if not self.model or not curModel or curModel:getCaptainID() ~= self.model:getCaptainID() then
            app:sendMsg("CaptainController", "closeMessageView")
        end 
        if self.currentTab == 1 then
            self:refreshMessageList()
            self:refreshMessageConfigs()
        end
    end

    self.msglistHandler = EM:on(app:getInst("CaptainController").MessageListChange, function()
        onChangeEvent()
    end)

    self.roomdataHandler = EM:on(app:getInst("CaptainController").RoomDataChange, function()
        onChangeEvent()
    end)

    self.redpointHandler =EM:on(app:getInst("CaptainModelRedPoint").RedPointChange, function()
        self:refreshRedPoint()
    end)
end

function CaptainMessageView:isSelf()
    if self.model and self.model:getCaptainID() == UD.uid then
        return true
    end
    return false
end

function CaptainMessageView:refreshRedPoint()
    if not self:isSelf() then
        self.tabs[1].dot:hide()
        self.tabs[2].dot:hide()
        return 
    end
    self.msgStamp = app:sendMsg("CaptainModelRedPoint", "getMessageRedPointStamp")
    self.visStamp = app:sendMsg("CaptainModelRedPoint", "getVisitorRedPointStamp")
    
    self.tabs[1].dot:setVisible(self.msgStamp > 0)
    self.tabs[2].dot:setVisible(self.visStamp > 0)

    if (self.msgStamp > 0 or self.visStamp > 0) and self.model then        
        app:sendMsg("CaptainController", "reqMessage", self.model:getCaptainID())
    end

    if self.currentTab == 1 then
        self:showMessagePanel()
    elseif self.currentTab == 2 then
        self:showVisitorPanel()
    end
end

function CaptainMessageView:checkAndSendSetting()
    local cd = self.model:getMessageConfig()
    if self.roomcfg.OnlyPermitFriends == cd.OnlyPermitFriends and
        self.roomcfg.OnlyFriendsCanSee == cd.OnlyFriendsCanSee and
        self.roomcfg.MessageAttention == cd.MessageAttention then
        return
    else
        app:sendMsg("CaptainController", "reqSetRoomConfig", self.roomcfg)
    end
end

function CaptainMessageView:initTabs()
    self.tabs = {}
    local btns = {}
    for i = 1, 3 do
        self.tabs[i] = {
            tab = self._root:findChild("Panel/Panel_tab/selected_btn_"..tostring(i)),
            dot = self._root:findChild("Panel/Panel_tab/selected_btn_"..tostring(i).."/dot"),
            name1 = self._root:findChild("Panel/Panel_tab/selected_btn_"..tostring(i).."/name_1"),
            name2 = self._root:findChild("Panel/Panel_tab/selected_btn_"..tostring(i).."/name_2"),
        }

        self.tabs[i].name2:hide()
        table.insert(btns, self.tabs[i].tab)
    end
    
    local function createGroup(aBtns)
        local g = {btns = aBtns}
        g.showname = function(btn, b)
            if btn:findChild("name_1") then
                btn:findChild("name_1"):setVisible(not b)
            end
            if btn:findChild("name_2") then
                btn:findChild("name_2"):setVisible(b)
            end
        end

        g.select = function(idx)
            g.reset()
            aBtns[idx]:setTouchEnabled(false)
            aBtns[idx]:setBright(false)
            g.showname(aBtns[idx], true)
        end
        g.reset = function()
            for i, b in ipairs(aBtns) do
                b:setTouchEnabled( true )
                b:setBright( true )
                g.showname(b, false)
            end
        end
        return g 
    end

    local function setCurrentTab(tabIdx)
        if self.currentTab == 3 then
            self:checkAndSendSetting()
        end
        self.currentTab = tabIdx
    end

    local group = createGroup(btns)
    group.select(1)
    btns[1].onClickEvt = function()
        setCurrentTab(1)
        self:hideAllPanel()
        self:showMessagePanel()
        group.select(1)
        if self:isSelf() then
            app:sendMsg("CaptainModelRedPoint", "reqRefreshRedPoint", 1)
        end
    end
    btns[2].onClickEvt = function()
        setCurrentTab(2)
        self:hideAllPanel()
        self:showVisitorPanel()
        group.select(2)
        self.clearVisit = true

        if self:isSelf() then
            app:sendMsg("CaptainModelRedPoint", "reqRefreshRedPoint", 3)
        end
    end
    btns[3].onClickEvt = function()
        setCurrentTab(3)
        self:hideAllPanel()
        self:showSettingPanel()
        group.select(3)
    end

    btns[1]:addTouchEventListener(btns[1].onClickEvt)
    btns[2]:addTouchEventListener(btns[2].onClickEvt)
    btns[3]:addTouchEventListener(btns[3].onClickEvt)

    self.selectTab = function(this, aTab)
        if aTab == 1 or aTab == 2 then
            btns[aTab].onClickEvt()
        else
            btns[1].onClickEvt()
        end
    end
end

function CaptainMessageView:initInputPanel()
    self.inputPanel = self._root:findChild("Panel/Panel_message")
    self.sendBtn = self._root:findChild("Panel/Panel_message/Panel_send/Button_enter")
    self.mikeBtn = self._root:findChild("Panel/Panel_message/Panel_send/Button_mike")

    self.textField = self._root:findChild("Panel/Panel_message/Panel_send/TextField")
    self.textField = display.replaceTextFieldWithEditBox(self.textField)

    self.sendBtn:addClickEventListener(function(sender) 
        local t = self.textField:getText()
        local sl = string.utf8len(t)
        if sl <= 0 then
            display.pushToast( L("captain_input_empty") )
        elseif sl > 30 then
            display.pushToast( L("captain_input_too_long") )
        else
            local function checkCB(str)
                if not cc.isDead(self) and not cc.isDead(self.textField) and self.model ~= nil then
                    app:sendMsg("CaptainController", "leaveMessage", self.model:getCaptainID(), str)
                    self.textField:setText("")
                end
            end

            app:sendMsg("CaptainController", "checkString", t, checkCB)
        end        
    end)
    self.mikeBtn:addClickEventListener(function(sender) end)
end

function CaptainMessageView:initMessageList()
    self.messageList = self._root:findChild("Panel/ListView_message")
end

function CaptainMessageView:initVisitorList()
    self.visitorList = self._root:findChild("Panel/ListView_visitors")
end

function CaptainMessageView:initEmptyTips()
    self.emptyTips = self._root:findChild("Panel/Panel_tips")
    self.emptyTips:hide()

    self.emptyTipsText = self._root:findChild("Panel/Panel_tips/text")
end

function CaptainMessageView:initSetingPanel()
    self.setPanel = self._root:findChild("Panel/set")
    local p = self.setPanel
    self.setOnlyFriendMsgBtn = p:findChild("Panel/set_1/selected_btn") 
    self.setOnlyFriendVisBtn = p:findChild("Panel/set_2/selected_btn") 
    self.setNotifyBtn = p:findChild("Panel/set_3/selected_btn") 

    self.setOnlyFriendMsgPanel = p:findChild("Panel/set_1") 
    self.setOnlyFriendVisPanel = p:findChild("Panel/set_2") 
    self.setNotifyPanel = p:findChild("Panel/set_3") 

    p:findChild("Panel/tlt"):setString(L"captainroom_socialRank")
    self.heads = {}
    for i = 1, 3 do
        self.heads[i] = {
            panel = p:findChild("Panel/Panel_"..tostring(i)),
            icon = p:findChild("Panel/Panel_"..tostring(i).."/head/icon"),
            name = p:findChild("Panel/Panel_"..tostring(i).."/name"),
            desc = p:findChild("Panel/Panel_"..tostring(i).."/text"),
        }
    end

    self.praiseLbl = p:findChild("Panel/Panel_text/text_1")
    self.visitLbl = p:findChild("Panel/Panel_text/text_2")
end

function CaptainMessageView:getCommonNode(msg)
    local ret = {}
    local n = self.listNode:clone()
    ret.node = n

    n:setContentSize(n:findChild("Panel"):getContentSize())

    ret.msgLbl = n:findChild("Panel/text_message")
    ret.lvPanel = n:findChild("Panel/Panel_lv")
    ret.timeLbl = n:findChild("Panel/Text_time")
    ret.nameLbl = n:findChild("Panel/Text_name")

    ret.addPanel = n:findChild("Panel/Panel_add")
    ret.headIcon = n:findChild("Panel/head/icon")
    ret.redDot = n:findChild("Panel/head/dot")

    ret.interactBtn = n:findChild("Panel/Button_3_0")

    ret.lvLbl = n:findChild("Panel/Panel_lv/text_lv")
    ret.classLbl = n:findChild("Panel/Panel_lv/Text_profession")
    
    if msg.Who.Uid == UD.uid then
        ret.interactBtn:hide()
    end

    return ret
end

function CaptainMessageView:userBaseDataFromWho(w)
    return {
        hairID = w.HairID,
        faceID = w.FaceID,
        hairColorID = w.HairColorID,
        raceID = w.RaceID,
        classID = w.ClassID,
        uid = w.Uid,
        name = w.Name,
        level = w.Lv,
        gender = w.Gender,
    }
end

function CaptainMessageView:getMessageNode(msg)
    local ret = self:getCommonNode(msg)

    -- local 
    local MsgType = rawget(msg, "MsgType")
    local isSys = false
    if MsgType then
        isSys = MsgType == "System"
    end
    if isSys then
        ret.msgLbl:setString(L(msg.Value))
    else
        ret.msgLbl:setString(msg.Value)
    end
    ret.msgLbl:show()

    ret.nameLbl:setString(msg.Who.Name)
    -- ret.timeLbl:setString(msg.Stamp)

    ret.addPanel:hide()
    ret.lvPanel:hide()

    local ubd = self:userBaseDataFromWho(msg.Who)
    local headIcon = ret.headIcon
    AvatarFactotry.getOrCreateHeroIconPath(
        ubd
        ,function(iconPath)
        if iconPath and not cc.isDead(headIcon) then
            headIcon:loadTexture(iconPath)
        end
    end)

    local off = app:sendMsg("CaptainController", "transTime", msg.Stamp)
    ret.timeLbl:setString(off)

    ret.interactBtn:addClickEventListener(function(sender)
        UIHandler:showHeadMenu(
            {type= Enums.MenuType.visitCaptainRoom, 
            attr=ubd, 
            pos=ret.interactBtn:convertToWorldSpace(cc.p(0,ret.interactBtn:getContentSize().height*0.5))
            })
    end)

    if self:isSelf() and checknumber(self.msgStamp) > 0 then
        ret.redDot:setVisible(checknumber(self.msgStamp) < msg.Stamp)
    end

    return ret
end

function CaptainMessageView:getVisitorNode(visitor)
    local ret = self:getCommonNode(visitor)

    ret.msgLbl:hide()

    ret.nameLbl:setString(visitor.Who.Name)
    -- ret.timeLbl:setString(msg.Stamp)

    ret.addPanel:hide()
    -- ret.lvPanel:hide()
    ret.lvLbl:setString(tostring(visitor.Who.Lv))
    ret.classLbl:setString(L("class_"..visitor.Who.ClassID))

    local ubd = self:userBaseDataFromWho(visitor.Who)
    local headIcon = ret.headIcon
    AvatarFactotry.getOrCreateHeroIconPath(
        ubd
        ,function(iconPath)
        if iconPath and not cc.isDead(headIcon) then
            headIcon:loadTexture(iconPath)
        end
    end)

    local off = app:sendMsg("CaptainController", "transTime", visitor.Stamp)
    ret.timeLbl:setString(off)

    ret.interactBtn:addClickEventListener(function(sender)
        UIHandler:showHeadMenu(
            {type= Enums.MenuType.visitCaptainRoom, 
            attr=ubd, 
            pos=ret.interactBtn:convertToWorldSpace(cc.p(0,ret.interactBtn:getContentSize().height*0.5))
            })
    end)

    if self:isSelf() and checknumber(self.visStamp) > 0 then
        ret.redDot:setVisible(checknumber(self.visStamp) < visitor.Stamp)
    end

    return ret
end

function CaptainMessageView:refreshMessageList()
    if not self.model then return end
    local messagelist = self.model:getMessages()
    self.emptyTips:hide()
    self.messageList:removeAllChildren()
    for i, v in ipairs(messagelist) do
        local n = self:getMessageNode(v)
        self.messageList:pushBackCustomItem(n.node)
    end
    if #messagelist <= 0 then
        self.emptyTipsText:setString(L"captain_social_no_message")
        self.emptyTips:show()
    end
end

function CaptainMessageView:refreshVisitorList()
    if not self.model then return end
    local messagelist = self.model:getVisitors()
    self.emptyTips:hide()
    self.visitorList:removeAllChildren()
    for i, v in ipairs(messagelist) do
        local n = self:getVisitorNode(v)

        self.visitorList:pushBackCustomItem(n.node)
    end
    if #messagelist <= 0 then
        self.emptyTipsText:setString(L"captain_social_no_visitor")
        self.emptyTips:show()
    end
end

function CaptainMessageView:hideAllPanel()
    self.messageList:hide()
    self.visitorList:hide()
    self.inputPanel:hide()
    self.emptyTips:hide()
    self.setPanel:hide()
end

function CaptainMessageView:showMessagePanel()
    self.messageList:show()
    self.inputPanel:show()
    self:refreshMessageList()
    self:refreshMessageConfigs()
end

function CaptainMessageView:showVisitorPanel()
    self.visitorList:show()
    self:refreshVisitorList()
end

function CaptainMessageView:showSettingPanel()
    -- self.model
    self.setPanel:show()

    if not self.model then return end 

    for i = 1, 3 do
        self.heads[i].panel:hide()
    end

    local rd = self.model:getRankData()
    table.sort(rd, function(a, b)
        return protobuf.enum_id("pb_captainRoom.InteractionType",a.Type) < protobuf.enum_id("pb_captainRoom.InteractionType", b.Type)
    end)
    for i, v in pairs(rd) do
        -- if v.Type == 1 then --点赞最多
        --     -- v.Who
        --     -- v.Num
            
        -- elseif v.Type == 2 then --留言最多
        -- elseif v.Type == 3 then --参观最多
        -- end

        local ubd = self:userBaseDataFromWho(v.Who)
        local headIcon = self.heads[i].icon
        AvatarFactotry.getOrCreateHeroIconPath(
            ubd
            ,function(iconPath)
            if iconPath and not cc.isDead(headIcon) then
                headIcon:loadTexture(iconPath)
            end
        end)
        self.heads[i].panel:show()
        self.heads[i].name:setString(v.Who.Name)
        self.heads[i].desc:setString(string.format(L("captain_rank_"..tostring(protobuf.enum_id("pb_captainRoom.InteractionType", v.Type))), v.Num))
    end

    if #rd <= 0 then
        self.setPanel:findChild("Panel/Panel_tips"):show()
        self.setPanel:findChild("Panel/Panel_tips/text"):setString(L("captain_message_setting_rank_no_data"))
    end
    
    self.visitLbl:setString(string.format(L("captain_visit_num"), self.model:getVisitNum())) 
    self.praiseLbl:setString(string.format(L("captain_praise_num"), self.model:getPraiseNum())) 

    local cd = self.model:getMessageConfig()
    self.roomcfg = {}
    self.roomcfg.OnlyPermitFriends = cd.OnlyPermitFriends
    self.roomcfg.OnlyFriendsCanSee = cd.OnlyFriendsCanSee
    self.roomcfg.MessageAttention = cd.MessageAttention

    local function refreshSettingState()
        self.setOnlyFriendMsgBtn:setBright(not self.roomcfg.OnlyPermitFriends)
        -- self.setOnlyFriendMsgBtn:setTouchEnabled(self.roomcfg.OnlyPermitFriends)
        self.setOnlyFriendMsgBtn:setTouchEnabled(false)

        self.setOnlyFriendVisBtn:setBright(not self.roomcfg.OnlyFriendsCanSee)
        -- self.setOnlyFriendVisBtn:setTouchEnabled(self.roomcfg.OnlyFriendsCanSee)
        self.setOnlyFriendVisBtn:setTouchEnabled(false)

        self.setNotifyBtn:setBright(not self.roomcfg.MessageAttention)
        -- self.setNotifyBtn:setTouchEnabled(self.roomcfg.MessageAttention)
        self.setNotifyBtn:setTouchEnabled(false)
    end

    self.setOnlyFriendMsgPanel:addClickEventListener(function(sender)
        self.roomcfg.OnlyPermitFriends = not self.roomcfg.OnlyPermitFriends
        refreshSettingState()
    end)
    
    self.setOnlyFriendVisPanel:addClickEventListener(function(sender)
        self.roomcfg.OnlyFriendsCanSee = not self.roomcfg.OnlyFriendsCanSee
        refreshSettingState()
    end)

    self.setNotifyPanel:addClickEventListener(function(sender)
        self.roomcfg.MessageAttention = not self.roomcfg.MessageAttention
        refreshSettingState()
    end)
    refreshSettingState()

    -- if cd.OnlyPermitFriends then
        
    -- end

    -- if cd.OnlyFriendsCanSee then
    -- end

    -- if cd.MessageAttention then
    -- end
end

function CaptainMessageView:refresh(m)
    self.model = m
    if m then
        self:refreshRedPoint()
        self:refreshMessageList()
        if self.model:getCaptainID() ~= UD.uid then
            self.tabs[3].tab:hide()
        end
        self:refreshMessageConfigs()
    end
end

function CaptainMessageView:refreshMessageConfigs()
    self.inputPanel:show()
    if self.model and self.model:getCaptainID() ~= UD.uid and not UD:isFriend(self.model:getCaptainID()) then
        if self.model:getMessageConfig().OnlyFriendsCanSee then
            self.messageList:removeAllChildren()
            self.inputPanel:hide()
            self.emptyTipsText:setString(L"captain_social_only_friend_can_see_message")
            self.emptyTips:show()
        end
    end
end

return CaptainMessageView